package com.sjy.project.ent.api;


import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;

import java.awt.image.BufferedImage;
import java.io.InputStream;
import java.net.URL;
import java.util.Date;
import java.util.List;

import javax.print.attribute.IntegerSyntax;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.apache.shiro.subject.Subject;
import org.apache.tomcat.util.codec.binary.Base64;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import com.sjy.common.constant.UserContext;
import com.sjy.common.entity.SecuryUserDetail;
import com.sjy.common.result.BaseResponse;
import com.sjy.common.utils.AesEncrypt;
import com.sjy.common.utils.DateUtils;
import com.sjy.common.utils.Md5Utils;
import com.sjy.common.utils.StringUtils;
import com.sjy.common.utils.TokenUtil;
import com.sjy.common.utils.WeChatUtils;
import com.sjy.framework.aspectj.lang.annotation.Log;
import com.sjy.framework.aspectj.lang.enums.BusinessType;
import com.sjy.framework.shiro.service.PasswordService;
import com.sjy.framework.web.controller.BaseController;
import com.sjy.project.ent.data.domain.EntData;
import com.sjy.project.ent.data.service.IEntDataService;
import com.sjy.project.ent.user.domain.EntUser;
import com.sjy.project.ent.user.service.IEntUserService;
import com.sjy.project.system.dept.service.IDeptService;
import com.sjy.project.system.user.domain.User;
import com.sjy.project.system.user.service.IUserService;

import cn.hutool.core.date.DateUtil;
import cn.hutool.crypto.digest.MD5;
import cn.hutool.http.HttpResponse;
import cn.hutool.http.HttpUtil;
import springfox.documentation.annotations.ApiIgnore;

@RestController
@Api(value = "亩均登录接口相关", tags = {"亩均接口"})
@RequestMapping({"/api/ent/login"})
public class ApiEntLoginController extends BaseController {
  @Autowired
  private IEntDataService entDataService;
  @Autowired
  private IEntUserService entUserService;
  @Autowired
  private IUserService userService;
  @Autowired
  private IDeptService deptService;
  @Autowired
  private PasswordService passwordService;
  
  @Autowired
  private TokenUtil tokenUtil;

  	@ApiOperation(value = "100.街道管理处登录", position = 100,notes = "用户名密码都经过aes加密")
	@SuppressWarnings("unchecked")
	@ApiImplicitParams({
       @ApiImplicitParam(required=false,name="loginName",value="aes加密后用户工号",example="123"),
       @ApiImplicitParam(required=false,name="password",value="aes加密后用户密码",example="123")
    })
	@RequestMapping(value = "/noToken/mgrLogin",method = RequestMethod.POST)
	@ResponseBody
	public ResponseEntity<BaseResponse<Object>> mgrLogin(@RequestParam(required = true) String loginName,String password,HttpServletRequest request) {
		try {
			loginName = AesEncrypt.decryptWithBase64(loginName);
			password = AesEncrypt.decryptWithBase64(password);
			if(StringUtils.isBlank(loginName)||StringUtils.isBlank(password)) {
				return BaseResponse.generateBadResponseEntity("参数异常", null);
			}
			UsernamePasswordToken loginToken = new UsernamePasswordToken(loginName, password, false);
	        Subject subject = SecurityUtils.getSubject();
	        try
	        {
	            subject.login(loginToken);
	        }
	        catch (AuthenticationException e)
	        {
	            e.printStackTrace();
	            return BaseResponse.generateBadResponseEntity("用户名或密码错误",null);
	        }
	        // 取身份信息
	        User user = getSysUser();
	        if(user==null) {
	        	return BaseResponse.generateBadResponseEntity();
	        }
			String token = this.tokenUtil.generateToken(user.getPhonenumber(), user.getUserType(),user.getUserId(), null,user.getUserName(),user.getLoginName());        
			user.setToken(token);
			//设置detpList 通过deptList返回当前账号所能看到的街道权限；；四个街道看到各自街道数据；街道上级账号，看到所有街道数据
			user.setDeptList(deptService.selectStreetDepts(user.getDeptId()));
			
			return BaseResponse.generateOKResponseEntity(user);
		}catch (Exception e) {
			return BaseResponse.generateBadResponseEntity("加密数据格式错误 解密异常!", e.getMessage());
		}
	}
  	
  	
  	@ApiOperation(value = "109.修改街道用户密码等", position = 109,notes = "")
	@SuppressWarnings("unchecked")
	@ApiImplicitParams({
       @ApiImplicitParam(required=true,name="oldPassword",value="aes加密后原始密码",example="123"),
       @ApiImplicitParam(required=true,name="newPassword",value="aes加密后新密码",example="123")
    })
	@RequestMapping(value = "/noToken/resetPwd",method = RequestMethod.POST)
	@ResponseBody
	public ResponseEntity<BaseResponse<Object>> resetPwd(@RequestParam(required = true) String oldPassword,@RequestParam(required = true) String newPassword) {
		try {
			oldPassword = AesEncrypt.decryptWithBase64(oldPassword);
			newPassword = AesEncrypt.decryptWithBase64(newPassword);
			User user = getSysUser();
	        if (!passwordService.matches(user, oldPassword))
	        {
	        	return BaseResponse.generateBadResponseEntity("修改密码失败，旧密码错误", null);
	        }
	        if (passwordService.matches(user, newPassword))
	        {
	        	return BaseResponse.generateBadResponseEntity("新密码不能与旧密码相同", null);
	        }
	        user.setPassword(newPassword);
	        user.setPwdUpdateDate(DateUtils.getNowDate());
	        if (userService.resetUserPwd(user) > 0)
	        {
	            setSysUser(userService.selectUserById(user.getUserId()));
	            return BaseResponse.generateOKResponseEntity();
	        }
			return BaseResponse.generateBadResponseEntity("修改密码异常，请联系管理员",null);
		}catch (Exception e) {
			return BaseResponse.generateBadResponseEntity("加密数据格式错误 解密异常!", e.getMessage());
		}
	}
  
  
  @ApiOperation(value = "200.企业登录", position = 200,notes = "用户名密码都经过aes加密")
	@SuppressWarnings("unchecked")
	@ApiImplicitParams({
     @ApiImplicitParam(required=false,name="creditCode",value="aes加密后 统代",example="91330301062029714G"),
     @ApiImplicitParam(required=false,name="password",value="aes加密后用户密码",example="123")
  })
	@RequestMapping(value = "/noToken/entLogin",method = RequestMethod.POST)
	@ResponseBody
	public ResponseEntity<BaseResponse<EntUser>> entLogin(@RequestParam(required = true) String creditCode,String password,HttpServletRequest request) {
		try {
			creditCode = AesEncrypt.decryptWithBase64(creditCode);
			password = AesEncrypt.decryptWithBase64(password);
			if(StringUtils.isBlank(creditCode)||StringUtils.isBlank(password)) {
				return BaseResponse.generateBadResponseEntity("参数异常", null);
			}
			
			EntUser su = new EntUser();
			su.setCreditCode(creditCode);
			su.setPassword(Md5Utils.hash(password));
			List<EntUser> entUsers = entUserService.selectEntUserList(su);
			if(entUsers==null||entUsers.size()==0) {
	        	return BaseResponse.generateBadResponseEntity("用户名或密码错误",null);
	        }
			EntUser user = entUsers.get(0);
			
			String token = this.tokenUtil.generateToken(user.getMobile(), "企业",user.getId(), null,user.getName(),user.getCreditCode());        
			user.setToken(token);
			//user登录会去查询是否有当年导入的去年ent_data数据
			EntData entData = entDataService.selectEntDataByCreditCode(creditCode, DateUtil.thisYear()-1);
			user.setEntData(entData);
			
			if(user.getFirstLogin()==1) {//非首次登录
				return BaseResponse.generateOKResponseEntity(user);
			}else {//首次登录
				return BaseResponse.generateWarnResponseEntity("首次登录请重置密码", user);
			}
			
		}catch (Exception e) {
			return BaseResponse.generateBadResponseEntity("加密数据格式错误 解密异常!", e.getMessage());
		}
	}
  
  @ApiOperation(value = "997.管理员重置企业密码", position = 997,notes = "")
	@SuppressWarnings("unchecked")
	@ApiImplicitParams({
		@ApiImplicitParam(required=false,name="creditCode",value="统代",example="1"),
		@ApiImplicitParam(required=false,name="newPassword",value="新密码",example="1"),
	})
	@RequestMapping(value = "/resetPwdByMgr",method = RequestMethod.POST)
	@ResponseBody
	public ResponseEntity<BaseResponse<EntUser>> resetPwdByMgr(String creditCode,String newPassword) {
		try {
			SecuryUserDetail tokenUser = UserContext.getUserSession();
			if(tokenUser==null) {
				return BaseResponse.generateBadResponseEntity("token无效!", null);
			}
			creditCode = AesEncrypt.decryptWithBase64(creditCode);
			newPassword = AesEncrypt.decryptWithBase64(newPassword);
			
			if(!"企业".equals(tokenUser.getUserType())) {//企业用户信息
				//获取企业用户信息
				EntUser user = entUserService.selectEntUserByCreditCode(creditCode);
				
				if(StringUtils.isBlank(newPassword)) {
					newPassword = StringUtils.substring(creditCode, StringUtils.length(creditCode)-6,StringUtils.length(creditCode));
					user.setFirstLogin(0);
				}
				user.setPassword(Md5Utils.hash(newPassword));
				entUserService.updateEntUser(user);
				return BaseResponse.generateOKResponseEntity("更新成功");
			}
			return BaseResponse.generateBadResponseEntity("无管理员权限",null);
			
		}catch (Exception e) {
			return BaseResponse.generateBadResponseEntity("统代或密码错误!", e.getMessage());
		}
	}
  	@ApiOperation(value = "998.重置企业密码成统代后6位；针对firstLogin是1 并且密码是123456的数据", position = 998,notes = "初始化表内数据")
	@SuppressWarnings("unchecked")
	@ApiImplicitParams({
		@ApiImplicitParam(required=false,name="status",value="状态 1",example="1"),
		@ApiImplicitParam(required=false,name="password",value="初始密码",example="123456"),
		@ApiImplicitParam(required=false,name="firstLogin",value="0初登 1非初登",example="0")
	})
	@RequestMapping(value = "/initEntUser",method = RequestMethod.POST)
	@ResponseBody
	public ResponseEntity<BaseResponse<EntUser>> initEntUser(@ApiIgnore EntUser entUser) {
		try {
			SecuryUserDetail tokenUser = UserContext.getUserSession();
			if(tokenUser==null||!"admin".equals(tokenUser.getLoginName())) {
				return BaseResponse.generateBadResponseEntity("token无效或无权限!", null);
			}
			//筛选出状态是1 、未登陆过、初始密码是123456 并且 有归属街道的数据
			List<EntUser> datas = entUserService.selectFirstLoginList(entUser);
			//遍历处理
			Date date = new Date();
			for(EntUser eUser:datas) {
				eUser.setUpdateTime(date);
				System.out.println(eUser.getCreditCode().substring(eUser.getCreditCode().length()-6, eUser.getCreditCode().length()));
				eUser.setPassword(Md5Utils.hash(eUser.getCreditCode().substring(eUser.getCreditCode().length()-6, eUser.getCreditCode().length())));
				entUserService.updateEntUser(eUser);
			}
			
			return BaseResponse.generateOKResponseEntity();
			
		}catch (Exception e) {
			return BaseResponse.generateBadResponseEntity("token信息异常!", e.getMessage());
		}
	}
  
  	@ApiOperation(value = "999.根据token获取用户信息，区分企业跟管理员", position = 999,notes = "无入参，直接取head中的token来获取用户数据")
	@SuppressWarnings("unchecked")
	@ApiImplicitParams({
	})
	@RequestMapping(value = "/getByToken",method = RequestMethod.POST)
	@ResponseBody
	public ResponseEntity<BaseResponse<EntUser>> getByToken(HttpServletRequest request) {
		try {
			SecuryUserDetail tokenUser = UserContext.getUserSession();
			if(tokenUser==null) {
				return BaseResponse.generateBadResponseEntity("token无效!", null);
			}
			
			if("企业".equals(tokenUser.getUserType())) {//企业用户信息
				EntUser user = entUserService.selectEntUserById(tokenUser.getUserId());
				
				String token = this.tokenUtil.generateToken(user.getMobile(), "企业",user.getId(), null,user.getName(),user.getCreditCode());        
				user.setToken(token);
				
				//user登录会去查询是否有当年导入的去年ent_data数据
				EntData entData = entDataService.selectEntDataByCreditCode(user.getCreditCode(), DateUtil.thisYear()-1);
				user.setEntData(entData);
				
				if(user.getFirstLogin()==1) {//非首次登录
					return BaseResponse.generateOKResponseEntity(user);
				}else {//首次登录
					return BaseResponse.generateWarnResponseEntity("首次登录请重置密码", user);
				}
			}else {//街道用户信息
				User user = getSysUser();
		        if(user==null) {
		        	user = userService.selectUserById(tokenUser.getUserId());
		        }
				String token = this.tokenUtil.generateToken(user.getPhonenumber(), user.getUserType(),user.getUserId(), null,user.getUserName(),user.getLoginName());        
				user.setToken(token);
				//设置detpList 通过deptList返回当前账号所能看到的街道权限；；四个街道看到各自街道数据；街道上级账号，看到所有街道数据
				user.setDeptList(deptService.selectStreetDepts(user.getDeptId()));
				return BaseResponse.generateOKResponseEntity(user);
			}
			
		}catch (Exception e) {
			return BaseResponse.generateBadResponseEntity("token信息异常!", e.getMessage());
		}
	}
  
}
